package com.ruoyi.framework.mybatisplus.util;

import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import lombok.SneakyThrows;

import javax.sql.DataSource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author yql
 * @describe MybatisTableFieldCacheUtils
 * @date 2023/3/11 15:49
 */

public class MysqlTableFieldCacheUtils {
    private static final ConcurrentHashMap<String, Set<String>> tableMap = new ConcurrentHashMap<>();

    @SneakyThrows
    public static void init(DataSource dataSource) {
        Db db = DbUtil.use(dataSource);
        List<Entity> list = db.query("select table_name, table_comment, create_time, update_time\n" +
                "from information_schema.tables\n" +
                "where table_schema = (select database())\n" +
                "order by create_time desc;");
        for (Entity entity : list) {
            String tableName = entity.getStr("table_name");
            List<Entity> entityList = db.query("select column_name ,column_key " +
                    " from information_schema.columns " +
                    " where table_schema = (select database()) " +
                    "  and table_name = (?) " +
                    " order by ordinal_position;", tableName);
            tableMap.put(tableName, entityList.stream().map(data -> {
                if (data.getStr("column_key").equals("PRI")) {
                    return "";
                }
                return data.getStr("column_name");
            }).collect(Collectors.toSet()));
        }
    }

    public static boolean existsFieldInTable(String tableName, String fieldName) {
        return tableMap.containsKey(tableName) && tableMap.get(tableName).contains(fieldName);
    }


}
